from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from rest_framework import serializers
from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.exceptions import AuthenticationFailed, TokenError
from rest_framework_simplejwt.exceptions import InvalidToken
from rest_framework_simplejwt.tokens import AccessToken

from Person.models import Person

User = get_user_model()


class LoginAuthenticate(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            person = User.objects.get(Q(username=username) | Q(email=username))
        except User.DoesNotExist:
            raise serializers.ValidationError("用户名或邮箱不存在")

        if person.check_password(password):
            return person
        else:
            raise serializers.ValidationError("密码错误")


class MyJSONWebTokenAuthentication(JWTAuthentication):
    def authenticate(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        if token:
            # 校验token是不是过期了，是不是合法，
            try:
                if "Bearer" in token:
                    token = token.split('Bearer ')[1].strip()
                access_token = AccessToken(token)
                person_name = access_token.payload.get('username')
                person = Person.objects.get(username=person_name)
                return person, access_token
            except TokenError as e:
                if isinstance(e, InvalidToken):
                    raise AuthenticationFailed('token不合法')
                else:
                    raise AuthenticationFailed('token过期')
        else:
            raise AuthenticationFailed('token没有携带')
